<style lang="less">
@import 'ruleAssignment.less';
</style>
<template>
  <div class="search">
    <Row>
      <Col>
      <Card>
        <Row>
          <Form ref="searchForm"
                :model="searchForm"
                inline
                :label-width="100"
                @submit.native.prevent
                class="search-form">

            <Form-item label="请选择公司"
                       prop="companyId">
              <Select v-model="searchForm.companyId"
                      @on-change="(event) => requestCarPageList()"
                      placeholder="请选择"
                      style="width:auto;">
                <Option v-for="item in companyList"
                        :value="item.value"
                        :key="item.value">{{ item.label }}
                </Option>
              </Select>
            </Form-item>

            <Form-item label="车牌号"
                       prop="licnum">
              <Input type="text"
                     v-model="searchForm.licnum"
                     clearable
                     placeholder="根据车牌号搜索"
                     style="width: 200px" />
            </Form-item>

            <Form-item style="margin-left:-35px;"
                       class="br">
              <Button @click="handleSearch"
                      type="primary"
                      icon="ios-search">
                搜索
              </Button>
              <Button @click="handleReset">重置</Button>
            </Form-item>
          </Form>
        </Row>

        <Row class="operation">
          <Button :disabled="!selectList.length"
                  @click="assign"
                  v-has="'assign'"
                  type="primary"
                  icon="md-add">分配规则
          </Button>
        </Row>

        <Row>
          <Alert show-icon>
            已选择
            <span class="select-count">{{selectCount}}</span> 项
            <a class="select-clear"
               @click="clearSelectAll">清空</a>
          </Alert>
        </Row>

        <Row type="flex">

          <Table :loading="loading"
                 border
                 :columns="columns"
                 :data="data"
                 sortable="custom"
                 @on-sort-change="changeSort"
                 @on-selection-change="showSelect"
                 ref="table"></Table>
          <Table :columns="exportColumns"
                 :data="exportData"
                 ref="exportTable"
                 style="display:none"></Table>

        </Row>
        <Row type="flex"
             justify="end"
             class="page">
          <Page :current="searchForm.current"
                :total="total"
                :page-size="searchForm.size"
                @on-change="changePage"
                @on-page-size-change="changePageSize"
                :page-size-opts="[10,20,50,100]"
                size="small"
                show-total
                show-elevator
                show-sizer></Page>
        </Row>
      </Card>
      </Col>
    </Row>

    <Modal :title="modalTitle"
           v-model="ruleAssignMentModalVisible"
           :mask-closable="false"
           :width="1000"
           :styles="{top: '100px'}">
      <Tree :data="ruleList"
            show-checkbox
            @on-check-change="onRuleListCheckChange"></Tree>
      <div slot="footer">

        <Button type="default"
                @click="ruleAssignMentModalVisible = false">取消
        </Button>
        <Button type="primary"
                :loading="submitLoading"
                @click="submitAssign">确定
        </Button>
      </div>
    </Modal>

    <Modal v-model="modalExportAll"
           title="确认导出"
           :loading="loadingExport"
           @on-ok="exportAll">
      <p>您确认要导出全部 {{total}} 条数据？</p>
    </Modal>

    <check-password ref="checkPass"
                    @on-success="resetPass" />
  </div>
</template>

<script>
import { getRuleList, getCompanyCombo, assignRules } from '@/api/index'

import { getCarPageList } from '@/api/operate'

import { validateMobile, validatePassword } from '@/libs/validate'
import { operationTypeSelect } from '@/libs/dict'
import { Message } from 'view-design'

import departmentChoose from '../../my-components/xboot/department-choose'
import departmentTreeChoose from '../../my-components/xboot/department-tree-choose'
import uploadPicInput from '../../my-components/xboot/upload-pic-input'
import circleLoading from '../../my-components/circle-loading.vue'
import checkPassword from '@/views/my-components/xboot/check-password'
import messageTip from '../../main-components/message-tip.vue'
import util from '@/libs/util'

export default {
  name: 'user-manage',
  components: {
    circleLoading,
    departmentChoose,
    departmentTreeChoose,
    uploadPicInput,
    checkPassword
  },
  data() {
    return {
      operationTypeList: operationTypeSelect,
      companyList: [],
      carList: [],
      ruleList: [],
      switchVal: true,
      loading: true,
      operationLoading: false,
      loadingExport: true,
      modalExportAll: false,
      drop: false,
      dropDownContent: '展开',
      dropDownIcon: 'ios-arrow-down',
      selectCount: 0,
      selectList: [],
      selectRuleList: [],
      dataDep: [],
      searchKey: '',
      searchForm: {
        operatorId: 0,
        companyId: 0,
        licnum: '',
        simCard: '',
        carState: 0,
        operationType: 0,
        cartypeId: 0,
        current: 1,
        size: 20
      },
      modalType: 0,
      ruleAssignMentModalVisible: false,
      modalTitle: '',
      ruleAssignmentForm: {
        carId: 3,
        operatorId: 2,
        companyId: 5,
        licnum: '粤B12115',
        carPic: '',
        plateColor: 3,
        cartypeId: 2,
        carState: 1,
        operationType: 4,
        retransmissionProtocol: 1,
        accessCode: '77483',
        deviceTypeId: 1,
        deviceModelId: null,
        deviceCompanyId: null,
        deviceSn: '1234541',
        simCard: '13512112345',
        videoType: null,
        isShuttlecar: 1,
        shuttleDate: null,
        carBrand: '',
        fuelType: null,
        roadLicenseNum: '',
        roadLicenseDate: null,
        engineNum: '',
        vinNum: '',
        imeiNum: '',
        businessScope: null,
        driveLicenseDate: null,
        driveLicense: '',
        driveLicensePath: '',
        operationLicensePath: '',
        seats: null,
        apprloadMass: null,
        totalMass: null,
        unladenMass: null,
        refuelType: null,
        quickmarkDate: null,
        carColor: null,
        length: null,
        wide: null,
        high: null,
        axlesNum: null,
        tireNum: null,
        carleaveDate: null,
        macAddress: '',
        register: true,
        remark: '',
        createBy: 'yl',
        carRules: null,
        createDate: '2019-10-16 14:00:00',
        companyName: '汉武科技',
        operatorName: '姬发',
        deviceName: null,
        deviceModel: null,
        manufacturer: null
      },
      errorPass: '',
      ruleAssignmentFormValidate: {},
      submitLoading: false,
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center',
          fixed: 'left'
        },
        {
          title: '序号',
          type: 'index',
          width: 65,
          align: 'center',
          fixed: 'left'
        },
        {
          title: '车牌号',
          key: 'licnum',
          minWidth: 120,
          align: 'center',
          sortable: true,
          fixed: 'left'
        },
        {
          title: '车辆类型',
          key: 'operationType',
          align: 'center',
          minWidth: 120,
          render: (h, params) => {
            if (params.row.operationType == 1) {
              return h('div', [
                h('Badge', {
                  props: {
                    status: 'success',
                    text: '航班客运'
                  }
                })
              ])
            } else if (params.row.operationType == 2) {
              return h('div', [
                h('Badge', {
                  props: {
                    status: 'success',
                    text: '旅游客运'
                  }
                })
              ])
            } else if (params.row.operationType == 3) {
              return h('div', [
                h('Badge', {
                  props: {
                    status: 'success',
                    text: '危险货物运输'
                  }
                })
              ])
            } else if (params.row.operationType == 4) {
              return h('div', [
                h('Badge', {
                  props: {
                    status: 'success',
                    text: '普通货运'
                  }
                })
              ])
            }
          },
          filters: [
            {
              value: 1,
              label: '班线客运'
            },
            {
              value: 2,
              label: '旅游客运'
            },
            {
              value: 3,
              label: '危险货物运输'
            },
            {
              value: 4,
              label: '普通货运'
            }
          ],
          filterMultiple: false,
          filterMethod(value, row) {
            return value == row.operationType
          }
        },
        {
          title: '对应规则',
          key: 'carRuleName',
          minWidth: 120,
          align: 'center'
        },
        /* {
             title: '车辆类型',
             key: 'carRules',
             align: "center",
             minWidth: 180,
             render: (h, params) => {
               let carRules = []
               if (params.row.carRules) {
                 carRules.push('进入围栏报警')
               }
               if (params.row.alarmOut) {
                 carRules.push('离开围栏报警')
               }
               if (params.row.alarmOverspeed) {
                 carRules.push('围栏内超速报警')
               }
               if (params.row.alarmTimeout) {
                 carRules.push('围栏内超时报警')
               }
               return h('span', carRules.join(','))
             }
           },*/
        {
          title: '最近操作时间',
          key: 'createDate',
          sortable: true,
          align: 'center',
          sortType: 'desc',
          minWidth: 180
        }
        /*   {
               title: "操作",
               key: "action",
               width: 80,
               align: "center",
               fixed: "right",
               render: (h, params) => {
                 return h("div", [
                   h(
                     "Button", {
                       props: {
                         type: "primary",
                         size: "small"
                       },
                       directives: [{
                         name: "has",
                         value: "assign"
                       }],
                       style: {
                         marginRight: "5px"
                       },
                       on: {
                         click: () => {
                           this.assign(params.row);
                         }
                       }
                     },
                     "分配"
                   ),
                 ]);
               }
             }*/
      ],
      exportColumns: [
        {
          title: '规则名',
          key: 'username'
        },
        {
          title: '头像',
          key: 'avatar'
        },
        {
          title: '所属部门ID',
          key: 'departmentId'
        },
        {
          title: '所属部门',
          key: 'departmentTitle'
        },
        {
          title: '手机',
          key: 'mobile'
        },
        {
          title: '邮箱',
          key: 'email'
        },
        {
          title: '规则类型',
          key: 'type'
        },
        {
          title: '状态',
          key: 'status'
        },
        {
          title: '删除标志',
          key: 'delFlag'
        },
        {
          title: '创建时间',
          key: 'createTime'
        },
        {
          title: '更新时间',
          key: 'updateTime'
        }
      ],
      data: [],
      exportData: [],
      total: 0
    }
  },
  computed: {
    showRuleFields: function() {
      let visible = true
      if (this.ruleType) {
        visible = true
      }
    }
  },
  methods: {
    init() {
      this.requestCompanyList()
    },
    changePage(v) {
      this.searchForm.current = v
      this.requestCarPageList()
      this.clearSelectAll()
    },
    changePageSize(v) {
      this.searchForm.size = v
      this.requestCarPageList()
    },
    selectDateRange(v) {
      if (v) {
        this.searchForm.startDate = v[0]
        this.searchForm.endDate = v[1]
      }
    },
    /*
     * 获取企业下拉框数据
     */
    requestCompanyList() {
      this.loading = true
      getCompanyCombo().then(res => {
        console.log('getCompanyCombo', res)
        this.loading = false
        if (res.code == 0) {
          this.companyList = res.data
          this.searchForm.companyId = util.min(this.companyList).value
          this.requestCarPageList()
        }
      })
    },

    /**
     * 请求数据列表
     */
    requestCarPageList() {
      this.loading = true
      getCarPageList(this.searchForm).then(res => {
        console.log('getCarPageList', res)
        this.loading = false
        if (res.code == 0) {
          this.data = res.data.records.map(item => {
            if (!item.carRuleName) {
              item.carRuleName = '尚无规则'
            }
            return item
          })
          this.total = res.data.total
        }
      })
    },

    requestRuleList(companyId) {
      this.loading = true
      getRuleList({
        companyId: companyId,
        current: 1,
        size: 20
      }).then(res => {
        console.log('requestRuleList', res)
        this.loading = false
        if (res.code == 0) {
          this.ruleList = []
          let csgz = {
            ruleType: 1,
            title: '超速规则',
            expand: true,
            children: []
          }
          let plgz = {
            ruleType: 2,
            title: '疲劳规则',
            expand: true,
            children: []
          }
          let qygz = {
            ruleType: 3,
            title: '区域规则',
            expand: true,
            children: []
          }
          let gjdgz = {
            ruleType: 4,
            title: '关键点规则',
            expand: true,
            children: []
          }
          let lxldgz = {
            ruleType: 5,
            title: '路线路段规则',
            expand: true,
            children: []
          }
          let clycgz = {
            ruleType: 6,
            title: '车辆异常规则',
            expand: true,
            children: []
          }
          res.data.records.forEach(item => {
            let obj = {}
            obj.title = item.ruleName
            obj.item = item
            if (item.ruleType == csgz.ruleType) {
              csgz.children.push(obj)
            } else if (item.ruleType == plgz.ruleType) {
              plgz.children.push(obj)
            } else if (item.ruleType == qygz.ruleType) {
              qygz.children.push(obj)
            } else if (item.ruleType == gjdgz.ruleType) {
              gjdgz.children.push(obj)
            } else if (item.ruleType == lxldgz.ruleType) {
              lxldgz.children.push(obj)
            } else if (item.ruleType == clycgz.ruleType) {
              clycgz.children.push(obj)
            }
          })
          this.ruleList.push(csgz, plgz, qygz, gjdgz, lxldgz, clycgz)
          this.ruleList = this.ruleList.map(item => {
            if (item.children.length) {
            } else {
              item.expand = false
              item.disabled = true
            }
            return item
          })
        }
      })
    },

    handleSearch() {
      this.searchForm.current = 1
      this.searchForm.size = 20
      this.clearSelectAll()
      this.requestCarPageList()
    },
    handleReset() {
      let tempForm = util.deepClone(this.searchForm)
      this.$refs.searchForm.resetFields()
      this.searchForm.companyId = tempForm.companyId
      this.searchForm.current = 1
      this.searchForm.size = 20
      // 重新加载数据
      this.requestCarPageList()
    },
    changeSort(e) {
      this.searchForm.sort = e.key
      this.searchForm.order = e.order
      if (e.order == 'normal') {
        this.searchForm.order = ''
      }
      this.requestCarPageList()
    },
    exportAll() {
      getAllUserData().then(res => {
        this.modalExportAll = false
        if (res.success) {
          this.exportData = res.result
          setTimeout(() => {
            this.$refs.exportTable.exportCsv({
              filename: '规则全部数据'
            })
          }, 1000)
        }
      })
    },
    submitAssign() {
      console.log('submitAssign')
      console.log('submitAssign selectList', this.selectList)
      console.log('submitAssign selectRuleList', this.selectRuleList)
      let carId = this.selectList.map(item => {
        return item.carId
      })
      let rules = this.selectRuleList.map(item => {
        return item.item.ruleId
      })
      assignRules({
        carId: carId.toString(),
        rules: rules.toString()
      }).then(res => {
        console.log('submitAssign assignRules', res)
        this.ruleAssignMentModalVisible = false
        this.handleSearch()
      })
    },
    assign() {
      console.log('assign', this.selectList)
      this.modalType = 1
      this.modalTitle = '分配规则'
      // this.ruleAssignmentForm = JSON.parse(JSON.stringify(v));
      this.ruleAssignMentModalVisible = true
      this.requestRuleList(this.searchForm.companyId)
    },
    showSelect(e) {
      console.log('showSelect', e)
      this.exportData = e
      this.selectList = e
      this.selectCount = e.length
    },
    clearSelectAll() {
      this.$refs.table.selectAll(false)
    },
    onCompanySelectChange(e) {
      console.log('onCompanySelectChange', e)
      this.searchForm.companyId = e
      this.requestCarPageList()
    },
    onRuleListCheckChange(e) {
      console.log('onRuleListCheckChange', e)
      this.selectRuleList = e.filter(item => {
        return !item.hasOwnProperty('children')
      })
    }
  },
  mounted() {
    this.init()
  }
}
</script>
